package com.gitee.limaozhi.socket.lesson02.example3;

import com.gitee.limaozhi.util.Utils;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * 粘包拆包
 *
 * @author hzlimaozhi
 * @date 2019/08/07 08:32
 */
public class Client {

    public static void main(String[] args) {
        Socket socket = null;
        try {
            // 创建套接字
            socket = new Socket();

            // 绑定本地地址、发起连接
            socket.connect(new InetSocketAddress(8000));
            System.out.println("客户端：建立连接：" + socket.getLocalSocketAddress().toString());

            // 读写通道
            OutputStream outputStream = socket.getOutputStream();

            String content = "第1次请求\n第2次请求\n第3次";
            outputStream.write(content.getBytes());

            Utils.sleepSeconds(5);

            content = "请求\n第4次请求\n第5次";
            outputStream.write(content.getBytes());

            // 关闭写通道：半关闭
            socket.shutdownOutput();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    // 关闭套接字
                    socket.close();
                    System.out.println("客户端：关闭");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
